import { Component, OnInit } from '@angular/core';
import { SelectionModel } from '@angular/cdk/collections';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { MatDialog } from '@angular/material';
import { Subscription } from 'rxjs';
import { filter } from 'rxjs/operators';
import { tap } from 'rxjs/operators';
import { Asset , AssetStatus, assetStatus, StatusNameMap, SearchType, SearchTypeMap } from '../../models/Asset';
import { Deliver } from '../../models/Deliver';
import { Department } from '../../models/Department';
import { User } from '../../models/User';
import { environment } from '../../environments/environment';
import { AssetAddComponent } from '../assetAdd/assetAdd';
import { ConfirmDialogComponent } from '../confirmDialog/confirmDialog';
import { AssignUpdateComponent } from '../assignUpdate/assignUpdate';
import { AssignHistoryComponent } from '../assignHistory/assignHistory';
import { ChangeHistoryComponent } from '../changeHistory/changeHistory';

import { AssetService } from '../../service/AssetService';
import { DeliverService } from '../../service/DeliverService';
import { AuthGuardService } from '../../service/AuthGuardService';
import { AssetType } from '../../models/AssetType';

@Component({
  templateUrl: './assetList.html',
  styleUrls: ['./assetList.css']
})
export class AssetListComponent implements OnInit {

  selection: SelectionModel<Asset>;
  assets: Asset[];
  deliver: Deliver[];
  assetTypes: AssetType[];
  total: number;
  isAdmin: boolean;
  cols = [ 'code', 'position', 'name', 'brand', 'version', 'type', 'status', 'createDate', 'department', 'user', 'assetImg', 'qrcode'];
  subscriptions: Subscription[] = [];
  pageSize = 8;
  page = 0;
  departments: Department[];
  users: User[];
  StatusNameMap = StatusNameMap;
  AssetStatus = AssetStatus;
  assetStatus = AssetStatus.IDLE;
  searchWord: string;
  SearchType = SearchType;
  SearchTypeMap = SearchTypeMap;
  assetName: string = null;
  assetUserId: number = null;
  assetDepartmentId: number = null;
  assetType: string = null;
  search: SearchType = SearchType.ALL;
  orderType :number;
  orders: string[];
  outQRCode: boolean;
  url: string = 'http://oa.sxycy.cn:8080/api/assetinfo/getlist?outQRCode=true&pageSize=999999';
  imgUrl: string;
  imgAppear: boolean;
  // assetStatus: string;
  constructor(
    private dialog: MatDialog,
    private route: ActivatedRoute,
    private router: Router,
    private assetService: AssetService,
    private  deliverService: DeliverService,
    private authGuardService: AuthGuardService
) { }

  ngOnInit() {
    this.orders = ['buyDate|desc'];
    this.authGuardService.checkAdmin().subscribe((isAdmin: boolean) => {
      this.isAdmin = isAdmin;
      if (this.isAdmin) {
        this.cols = ['code', 'name', 'brand', 'version', 'type', 'status', 'createDate', 'department', 'user',
          'assetImg', 'operate'];
      } else {
        this.cols = this.cols.filter(col => col  !== 'operate');
      }
    });

    this.subscriptions[1] = this.route.data
      .subscribe((
        data: {
          users: { users: User[], total: number},
          assetTypes:  AssetType[],
          departments: {departments: Department[], total: number}
        }) => {
        this.departments = data.departments.departments;
        this.users = data.users.users;
        this.assetTypes = data.assetTypes;
      });
    const initialSelection = [];
    const allowMultiSelect = true;
    this.selection = new SelectionModel<Asset>(allowMultiSelect, initialSelection);
    this.update(this.page).subscribe((res) => {
      this.assets = res.res;
      this.total = res.total;
    })
  }

  isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = this.assets.length;
    return numSelected === numRows;
  }

  allToggle() {
    this.isAllSelected() ?
      this.selection.clear() :
      this.assets.forEach(row => this.selection.select(row));
  }

  onOpenAdd() {
    this.authGuardService.checkLogin().pipe(filter(res => res)).subscribe(() => {
      const dialogRef = this.dialog.open(AssetAddComponent, {
        width: '700px',
        height: '550px',
        data: {
          departments: this.departments,
          users: this.users,
          assetTypes: this.assetTypes
        }
      });
      dialogRef.afterClosed().subscribe((result) => {
        this.update(this.page).subscribe();
      });
    });
  }

  onOpenEdit(asset: Asset) {
    this.authGuardService.checkLogin().pipe(filter(res => res)).subscribe(() => {
      const dialogRef = this.dialog.open(AssetAddComponent, {
        width: '700px',
        height: '550px',
        data: {
          asset: asset,
          departments: this.departments,
          users: this.users,
          assetTypes: this.assetTypes,
        }
      });
      dialogRef.afterClosed().subscribe((result) => {
        this.update(this.page).subscribe();
      });
    });
  }

  onDelete(id: string) {
    this.authGuardService.checkLogin().pipe(filter(res => res)).subscribe(() => {
      const dialogRef = this.dialog.open(ConfirmDialogComponent, {
        width: '400px',
        height: '200px',
        data: {message: '确认删除？'}
      });
      dialogRef.afterClosed().subscribe((result) => {
        if (result) {
          this.assetService.del(id).subscribe((res) => {
            if (res.success) {
              this.update(this.page).subscribe();
            }
          });
        }
      });
    });
  }
  onAssign(asset: Asset) {
    this.authGuardService.checkLogin().pipe(filter(res => res)).subscribe(() => {
      const dialogRef = this.dialog.open(AssignUpdateComponent, {
        width: '500px',
        height: '400px',
        data: {
          asset: asset,
          users: this.users
        }
      });
      dialogRef.afterClosed().subscribe((result) => {
        this.update(this.page).subscribe();
      });
    });
  }

  assignHistory(asset: Asset) {
    this.authGuardService.checkLogin().pipe(filter(res => res)).subscribe(() => {
      const dialogRef = this.dialog.open(AssignHistoryComponent, {
        width: '500px',
        height: '400px',
        data: {
          asset: asset
        }
      });
      dialogRef.afterClosed().subscribe((result) => {
        this.update(this.page).subscribe();
      });
    });
  }

  changeHistory(asset: Asset) {
    this.authGuardService.checkLogin().pipe(filter(res => res)).subscribe(() => {
      const dialogRef = this.dialog.open(ChangeHistoryComponent, {
        width: '500px',
        height: '700px',
        data: {
          asset: asset
        }
      });
      dialogRef.afterClosed().subscribe((result) => {
        this.update(this.page).subscribe();
      });
    });
  }

  update(page: number = 1) {
    if (this.assetStatus === AssetStatus.IDLE) {
      this.orderType = 0;
    } else {
      this.orderType = 2;
    }
    const options: any = { assetName: this.assetName, assetUserId: this.assetUserId, assetDepartmentId: this.assetDepartmentId, assetType: this.assetType, assetStatus: String(this.assetStatus), orders: this.orders, outQRCode: this.outQRCode};
    return this.assetService.getAssets(page, this.pageSize, options).pipe(tap((res) => {
      this.assets = res.res;
      this.total = res.total;
      this.page = page;
    }));
  }

  onUpdateCode(assetId) {
    this.assetService.updateCode(assetId).subscribe();
  }
  onSearchChange(search) {
    this.search = search;
    if (this.search === SearchType.ALL) {
      this.assetName = null;
      this.assetUserId = null;
      this.assetDepartmentId = null;
      this.assetType = null;
      this.update(this.page).subscribe();
    }
  }

  searchAsset() {
    this.assetName = this.searchWord;
    this.assetUserId = null;
    this.assetDepartmentId = null;
    this.assetType = null;
    this.update(this.page).subscribe();
  }

  trackById(index: number, item: any) {
    return item.id;
  }

  onPageChanged(page: number) {
    this.update(page).subscribe();
  }

  onUserChange(assetUserId: number) {
    this.assetUserId = assetUserId;
    this.assetDepartmentId = null;
    this.update(this.page).subscribe();
  }

  onDepartmentChange(assetDepartmentId: number) {
    this.assetUserId = null;
    this.assetDepartmentId = assetDepartmentId;
    this.update(this.page).subscribe();
  }

  onAssetChange(assetName: string) {
    this.assetName = assetName;
    this.update(this.page).subscribe();
  }

  onStatusChange(assetStatus: AssetStatus) {
    this.assetStatus = assetStatus;
    if (this.assetStatus === AssetStatus.USE) {
      this.cols = ['code', 'position', 'name', 'brand', 'version', 'type', 'status', 'createDate', 'department', 'user',
        'assetImg', 'qrcode', 'operate'];
    } else {
      this.cols = ['code', 'name', 'brand', 'version', 'type', 'status', 'createDate', 'department', 'user',
        'assetImg',  'operate'];
    }
    this.update(this.assetStatus).subscribe();

  }
  onTypeChange(assetType: string) {
    this.assetType = assetType;
    this.update(this.page).subscribe();
  }

  onOrderChange(orderType) {
    this.orderType = orderType;
    switch (this.orderType) {
      case 1:
        this.orders = [];
        this.orders.push('buyDate|asc');
        break;
      case 2:
        this.orders = [];
        this.orders.push('assetPrice|asc');
        break;
      case 0:
      default:
        this.orders.push('buyDate|desc');
    }
    this.update(this.page).subscribe();
  }

  bigImg(imgUrl) {
    this.imgUrl = imgUrl;
    this.imgAppear = true;
  }

  closeImg() {
    this.imgAppear = false;
    this.imgUrl = '';
  }

  onExportCode() {
    this.outQRCode = true;
    // window.location.href = 'http://oa.sxycy.cn:8080/api/assetinfo/getlist?outQRCode=true';
    // const href = `${this.url}&assetName=${this.assetName}&assetUserId=${this.assetUserId}&assetDepartmentId=${this.assetDepartmentId}&assetType=${this.assetType}&assetStatus=${this.assetStatus}&pageSize=999999`;
    if (this.assetName) {
      this.url += `&assetName=${this.assetName}`;
    }
    if (this.assetUserId) {
      this.url += `&assetUserId=${this.assetUserId}`;
    }
    if (this.assetDepartmentId) {
      this.url += `&assetDepartmentId=${this.assetDepartmentId}`;
    }
    if (this.assetType) {
      this.url += `&assetType=${this.assetType}`
    }
    if (String(this.assetStatus))  {
      this.url += `&assetStatus=${this.assetStatus}`;
    }
    // if (this.orders.length !== 0) {
    //   this.url += `&orders=${this.orders}`;
    // }
        const a = window.open(this.url);
        const loop = setInterval(() => {
         if (a.closed) {
           clearInterval(loop);
           parent.location.reload();
         }
        }, 1);
    }
  }
